package com.petdog.module.community.controller;

import com.petdog.common.dto.ApiResponse;
import com.petdog.module.community.dto.JoinCommunityRequest;
import com.petdog.module.community.dto.CommunityMemberResponse;
import com.petdog.module.community.service.UserCommunityService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;

/**
 * 用户社区关联控制器
 */
@RestController
@RequestMapping
public class UserCommunityController {
    
    @Autowired
    private UserCommunityService userCommunityService;
    
    /**
     * 加入社区
     */
    @PostMapping("/api/communities/{communityId}/members")
    public ApiResponse<Boolean> joinCommunity(@PathVariable Long communityId, @RequestBody JoinCommunityRequest request) {
        // 设置社区ID
        request.setCommunityId(communityId);
        
        // 参数验证
        if (request.getUserId() == null || request.getUserId() <= 0) {
            return ApiResponse.error("用户ID无效", "INVALID_USER_ID");
        }
        
        if (communityId == null || communityId <= 0) {
            return ApiResponse.error("社区ID无效", "INVALID_COMMUNITY_ID");
        }
        
        try {
            boolean success = userCommunityService.joinCommunity(request);
            if (success) {
                return ApiResponse.success(true, "加入成功");
            } else {
                return ApiResponse.error("加入失败，您可能已经加入该社区", "ALREADY_JOINED");
            }
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage(), "INVALID_PARAMS");
        } catch (SecurityException e) {
            return ApiResponse.error(e.getMessage(), "FORBIDDEN");
        } catch (Exception e) {
            return ApiResponse.error("操作失败，请重试", "SERVER_ERROR");
        }
    }

    /**
     * 退出社区
     */
    @DeleteMapping("/api/communities/{communityId}/members/me")
    public ApiResponse<Boolean> leaveCommunity(@PathVariable Long communityId, @RequestParam Long userId) {
        // 参数验证
        if (userId == null || userId <= 0) {
            return ApiResponse.error("用户ID无效", "INVALID_USER_ID");
        }
        
        if (communityId == null || communityId <= 0) {
            return ApiResponse.error("社区ID无效", "INVALID_COMMUNITY_ID");
        }
        
        try {
            boolean success = userCommunityService.leaveCommunity(userId, communityId);
            if (success) {
                return ApiResponse.success(true, "退出成功");
            } else {
                return ApiResponse.error("退出失败，创建者不能退出社区", "CANNOT_LEAVE");
            }
        } catch (IllegalArgumentException e) {
            return ApiResponse.error(e.getMessage(), "INVALID_PARAMS");
        } catch (SecurityException e) {
            return ApiResponse.error(e.getMessage(), "FORBIDDEN");
        } catch (Exception e) {
            return ApiResponse.error("操作失败，请重试", "SERVER_ERROR");
        }
    }

    /**
     * 获取社区成员列表
     */
    @GetMapping("/api/communities/{communityId}/members")
    public ApiResponse<List<CommunityMemberResponse>> getCommunityMembers(
            @PathVariable Long communityId,
            @RequestParam(defaultValue = "1") int page,
            @RequestParam(defaultValue = "20") int pageSize) {
        if (communityId == null || communityId <= 0) {
            return ApiResponse.error("社区ID无效", "INVALID_COMMUNITY_ID");
        }
        
        List<CommunityMemberResponse> members = userCommunityService.getCommunityMembers(communityId, page, pageSize);
        return ApiResponse.success(members);
    }

    /**
     * 获取社区成员数量
     */
    @GetMapping("/api/communities/{communityId}/members/count")
    public ApiResponse<Integer> getCommunityMemberCount(@PathVariable Long communityId) {
        if (communityId == null || communityId <= 0) {
            return ApiResponse.error("社区ID无效", "INVALID_COMMUNITY_ID");
        }
        
        int count = userCommunityService.getCommunityMemberCount(communityId);
        return ApiResponse.success(count);
    }
    
    /**
     * 检查用户是否为社区管理员
     */
    @GetMapping("/community/{communityId}/admin-check")
    public ApiResponse<Boolean> isCommunityAdmin(@PathVariable Long communityId, @RequestParam Long userId) {
        boolean isAdmin = userCommunityService.isCommunityAdmin(userId, communityId);
        return ApiResponse.success(isAdmin);
    }
}